from ..database import database

from peewee import *
from .offer import Offer

import datetime


class Inventory(database.Model):
    id = PrimaryKeyField(db_column='id', help_text='id')
    offer = ForeignKeyField(Offer, help_text='所属报价')
    status = CharField(db_column='status', help_text='状态')
    created_at = DateTimeField(default=datetime.datetime.now)
    updated_at = DateTimeField(default=datetime.datetime.now)

    # @classmethod
    # def lock(cls, offer, num):
    #     inventory_list = list(
    #         cls.select().where(Inventory.status == 'normal').where(Inventory.offer == offer).limit(num))
    #
    #     if len(inventory_list) < num: return None
    #
    #     update_id_list = [x.id for x in inventory_list]
    #     cls.update(Inventory.status = 'pre-shipped').where(Inventory.id == update_id_list).execute()
    #
    #     return inventory_list

    @classmethod
    def delivery_with_offer(cls, offer, num):
        inventory_list = list(
            cls.select().where(Inventory.status == 'normal').where(Inventory.offer == offer).limit(num))

        if len(inventory_list) < num: return None

        update_id_list = [x.id for x in inventory_list]
        query = cls.update(status='shipped').where(cls.id == update_id_list)
        query.execute()
        return inventory_list

    @classmethod
    def get_by_offer(cls, offer):
        return cls.select().where(Inventory.status == 'delivered').where(Inventory.offer == offer)


class Ticket(Inventory, database.Model):
    value = CharField(db_column='value', help_text='票据值')
    key = CharField(db_column='key', help_text='票据key',null=True)

    # class Meta:
    #     db_table = '{}_tickets'.format(TABLE_PREFIX)
